/*
 *  maskGenerate.c
 *  Ball and Plate
 *
 *  Created by Kenn Sebesta on 2007-11-22.
 *  Copyright 2007 __MyCompanyName__. All rights reserved.
 *
 */

#include "maskGenerate.h"

void PrintMat(CvMat *);

IplImage* maskGenerate( double ballDia, double camCal )
{
	IplImage* maskImage;
	double ballRadPix, t;
	int maskSize;
	
	// Determines maskImage size based on the resolution
	ballRadPix=camCal*ballDia/2;
	maskSize=cvRound(ballRadPix)*2+1;
	
	// Creates the maskImage prototype
	maskImage = cvCreateImage( cvSize(maskSize, maskSize),  IPL_DEPTH_8U, 1 );
	cvZero(maskImage);
	
	//Creates the circle representing the ball
	for (t=0;t<=6.27;t+=0.01) {
		cvSetReal2D( maskImage, cvRound((maskSize-1)/2+ballRadPix*cos(t)), cvRound((maskSize-1)/2+ballRadPix*sin(t)), 255 );	
	}
	
	return maskImage;
}

void maskDFT( int dft_rows, int dft_cols, int missingCount, IplImage *maskImage, CvMat **dft_mIm )
{ /*	This function precomputes the DFT of the maskImage. This saves considerable time. 
		However, since the maskImage DFT changes with a varying crop size, it is useful 
		to consider precomputing all the possiblities, since they are fixed by the size steps
		in the cropping algorithm.
 */
	if( missingCount!=0) //Only redo the transformation if the crop size has changed.
	{
                //      cvReleaseData( *dft_mIm );
                cvReleaseMat( dft_mIm );
                *dft_mIm=cvCreateMat( dft_rows, dft_cols, CV_32F );

		CvMat tmp;
		IplImage *maskImageF;
		maskImageF= cvCreateImage(cvGetSize(maskImage),  IPL_DEPTH_32F, 1); //Edge matrix in F32
		cvConvert( maskImage, maskImageF ); //Change from integer to float

                // Pad dft_mIm with zeros
		cvGetSubRect( *dft_mIm, &tmp, cvRect( 0, 0, maskImage->width, maskImage->height ));
		cvCopy( maskImageF, &tmp );
		cvGetSubRect( *dft_mIm, &tmp, cvRect( maskImage->width, 0, dft_cols - maskImage->width, maskImage->height ));
		cvZero( &tmp );
		// No need to pad bottom part of dft_mIm with zeros because of use of non-zero rows parameter in cvDFT() calls below
		cvDFT( *dft_mIm, *dft_mIm, CV_DXT_FORWARD, maskImage->height );

		//Garbage Collection
		cvReleaseImage(&maskImageF);
	}
	

	
	return;
}
